package com.thread.syn3;

/**
 * 死锁
 *
 * 没有同步就没有死锁
 * 过多的同步方法可能导致死锁
 *
 * @author jiangbang
 * @date 2016/7/21
 */
public class synDemo03 {
    public static void main(String[] args) {
        Object goods = new Object();
        Object money = new Object();
        Test1 test1 = new Test1(goods,money);
//        Test2 test2 = new Test2(goods,money);
        Thread thread = new Thread(test1);
//        Thread thread2 = new Thread(test2);
        thread.start();
//        thread2.start();
    }
}

class Test1 implements Runnable{
    Object goods;
    Object money ;
    public Test1( Object goods,Object money){
        this.goods = goods;
        this.money = money;
    }
    @Override
    public void run() {
        while (true){
            test();
        }
    }
    public void test(){
        synchronized (goods){
            try {
                Thread.sleep(500); //增加死锁的可能性
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (money){
            }
        }
        System.out.println("一手给钱");
    }
}

class Test2 implements Runnable{
    Object goods;
    Object money ;
    public Test2( Object goods,Object money){
        this.goods = goods;
        this.money = money;
    }
    @Override
    public void run() {
        while (true){
            test();
        }
    }
    public void test(){
        synchronized (money){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (goods){
            }
            System.out.println("一手给货");
        }
    }
}